<template>
  <transition name="slide">
    <music-list :songs="songs" :title="title" :bg-image="bgImage"></music-list>
  </transition>
</template>

<script>
  import {mapGetters} from 'vuex'; // 通过包装后的getters 来获取 state中singer的数据
  import {getSingerDetail,getMusic} from "api/singer";
  import {ERR_OK} from "api/config";
  import {createSong} from "common/js/song";
  import MusicList from 'components/music-list/music-list'; // 引入组件



  export default {
    name: "singer-detail",
    data () {
      return {
        songs: []
      }
    },
    // 通过mapGetters来获取state中singer的数据
    computed: {
      ...mapGetters([
        'singer'
      ]),
      // 歌曲详情的title
      title () {
        return this.singer.name
      },
      // 封面
      bgImage () {
        return this.singer.avatar
      }
    },
    created () {
      this._getDetail(); // 获取到歌手的详情信息
      console.log("singer", this.singer);
    },
    methods: {
      _getDetail () {
        // 如果用户在歌手详情页面刷新时，没有 singerId的话，就回退到singer页面
        if (!this.singer.id) {
          this.$router.push('/singer');
          return
        }
        getSingerDetail(this.singer.id).then((res) => {
          if (res.code === ERR_OK) {
            this.songs = this._normallizeSongs(res.data.list);
            console.log(this.songs);
          }
        })
      },
      _normallizeSongs (list) {
        // let ret = [];
        // list.forEach((item,index) => {
        //   let {musicData} = item;
        //   if (musicData.songid && musicData.albummid) {
        //     ret.push(createSong(musicData));
        //   }
        // });
        // return ret
        //
        let ret = [];
        if (!list) {
          return;
        }
        list.forEach( (item) => {
          let {musicData} = item;
          // createSong 必传两个参数
          if (musicData.songid && musicData.albummid) {
            getMusic(musicData.songmid).then( (res) => {
              if (res.code === ERR_OK) {
                const svkey = res.data.items;
                const songVkey = svkey[0].vkey;
                const newSong = createSong(musicData,songVkey);
                ret.push(newSong);
              }
            })
          }
        });
        return ret;
      }
    },
    // 注册组件
    components: {
      MusicList
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .slide-enter-active, .slide-leave-active
    transition all 0.3s

  .slide-enter, .slide-leave-active
    transform translate3d(100%, 0, 0)
</style>
